package com.jae.service.impl;

import com.jae.mapper.RoleRescMapper;
import com.jae.mapper.UserMapper;
import com.jae.mapper.UserRoleMapper;
import com.jae.model.roleResc.RoleRescDTO;
import com.jae.model.user.User;
import com.jae.model.userRole.UserRoleDTO;
import com.jae.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 用户权限
 */

@Service
public class LoginServiceImpl extends BaseServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleRescMapper roleRescMapper;
    @Override
    public User loadUserByUsername(String username){
        log.debug(username);
        Map map = new HashMap();
        map.put("username",username);
        map.put("is_deleted",-1);
        User user = userMapper.findByUsername(map);
        if(user != null){
            map = new HashMap();
            map.put("user_id",user.getUser_id());
            //查询用户的角色
            List<UserRoleDTO> userRoles = userRoleMapper.findAll(map);
            user.setRoles(listRoles(userRoles));
            //权限集合
            Collection<? extends GrantedAuthority> authorities = merge(userRoles);
            user.setAuthorities(authorities);
            return user;
        }
        return null;

    }

    private List<String> listRoles(List<UserRoleDTO> userRoles){
        List<String> list=new ArrayList<>();
        if (!CollectionUtils.isEmpty(userRoles)){
            userRoles.forEach(param-> list.add(param.getRole_name()));
        }
        return list;
    }

    private List<String> listAuths(List<UserRoleDTO> userRoles){
        List<String> list=new ArrayList<>();
        if (!CollectionUtils.isEmpty(userRoles)){
            userRoles.forEach(param->{
                List<RoleRescDTO> roleAuths = roleRescMapper.findByRoleId(param.getRole_id());
                //查询权限
                if (!CollectionUtils.isEmpty(roleAuths)){
                    roleAuths.forEach(auth->list.add(auth.getResc_url()));
                }
            });
        }
        return list;
    }

    private Collection<? extends GrantedAuthority> merge(List<UserRoleDTO> userRoles){
        List<String> roles = listRoles(userRoles);
//        List<String> auths = listAuths(userRoles);
        String[] a={};
//        roles.addAll(auths);
        return AuthorityUtils.createAuthorityList(roles.toArray(a));
    }
}
